package controllers

import (
	"gin-web-demo/models"
	"gin-web-demo/utils"
	"net/http"

	"github.com/gin-gonic/gin"
)

type FsoController struct{}

// GetFsos 获取所有汛情数据
func (fs *FsoController) GetFsos(c *gin.Context) {
	var fsos []models.Fso
	if err := utils.DB.Find(&fsos).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, fsos)
}

// GetFso 获取单个汛情数据
func (fs *FsoController) GetFso(c *gin.Context) {
	id := c.Param("id")
	var fso models.Fso
	if err := utils.DB.First(&fso, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Fso not found"})
		return
	}
	c.JSON(http.StatusOK, fso)
}

// CreateFso 创建汛情数据
func (fs *FsoController) CreateFso(c *gin.Context) {
	var fso models.Fso
	if err := c.ShouldBindJSON(&fso); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := utils.DB.Create(&fso).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, fso)
}

// UpdateFso 更新汛情数据
func (fs *FsoController) UpdateFso(c *gin.Context) {
	id := c.Param("id")
	var fso models.Fso
	if err := utils.DB.First(&fso, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Fso not found"})
		return
	}

	if err := c.ShouldBindJSON(&fso); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := utils.DB.Save(&fso).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, fso)
}

// DeleteFso 删除汛情数据
func (fs *FsoController) DeleteFso(c *gin.Context) {
	id := c.Param("id")
	var fso models.Fso
	if err := utils.DB.First(&fso, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Fso not found"})
		return
	}

	if err := utils.DB.Delete(&fso).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Fso deleted successfully"})
}
